package com.yangle.shell.service.impl;

import com.yangle.shell.bean.ProductInfo;
import com.yangle.shell.dao.ProductInfoRepository;
import com.yangle.shell.dto.CartDto;
import com.yangle.shell.enums.ExceptionTypeEnum;
import com.yangle.shell.enums.ProductInfoStatusEnum;
import com.yangle.shell.exception.SellException;
import com.yangle.shell.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author: yangle
 * Create Data: 2020/12/4
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository repository;

    @Override
    public List<ProductInfo> getUpAll() {
        return repository.getByProductStatus(ProductInfoStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> getAll(Pageable pageable) {

        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo findOne(String productId) {
        return repository.findById(productId).get();
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo);
    }

    @Override
    public void increaseStock(List<CartDto> cartDtoList) {

    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDto> cartDtoList) {
        for (CartDto cartDto:cartDtoList){
            ProductInfo productInfo = repository.getOne(cartDto.getProductId());
            if(productInfo==null){
                throw new SellException(ExceptionTypeEnum.PRODUCT_NOT_EXIST.getMessage());
            }
            int amount = productInfo.getProductStock()-cartDto.getProductQuantity();
            if (amount<0){
                throw new SellException(ExceptionTypeEnum.PRODUCT_STOCK_OUT.getMessage());
            }
            productInfo.setProductStock(amount);
            repository.save(productInfo);
        }
    }

    @Override
    public ProductInfo downProduct(String productId) {
        ProductInfo productInfo = findOne(productId);
        if(productInfo!=null){
            productInfo.setProductStatus(ProductInfoStatusEnum.DOWN.getCode());
            productInfo = repository.save(productInfo);
        }
        return productInfo;
    }
}
